<?php
/**
 * Created by PhpStorm.
 * User: xieky
 * Date: 2017-05-03
 * Time: 09:47
 */

namespace common\helpers;


class CurlHelper {
    /**
     * @param $url string 请求的URL地址
     * @param bool $curl_post  是否POST,默认GET
     * @param bool $curl_cookie 是否传递COOKIE信息，请求处理需要获取当前用户时，传递当前COOKIE的SSOID
     * @return []
     */
    public static function getCurlData($url,$curl_post=false,$curl_cookie=true,$postData=null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, $curl_post);
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        if($curl_post && !empty($postData))
        {
            curl_setopt($ch,CURLOPT_POSTFIELDS,$postData);
        }
        if ($curl_cookie && !empty($_COOKIE["ssoid"])) {
            $strCookie = "ssoid=" . $_COOKIE["ssoid"];
            curl_setopt($ch, CURLOPT_COOKIE, $strCookie);
        }
        $data = curl_exec($ch);
        curl_close($ch);
        if(!empty($data))
        {
            $tmpArr=preg_split("/callback=/",$url);
            $callback="";
            if(count($tmpArr)>=2)
            {
                $callback=$tmpArr[1];
                if(strpos($callback,"&")>0)
                {
                    $callback=substr($callback,0,strpos($callback,"&"));
                }
            }
            $data=rtrim(ltrim($data,$callback."("),")");
        }
        return json_decode($data);
    }
}